<template>
  <div class="nav-tab">
    <el-tabs
      v-model="activeName"
      class="demo-tabs"
      @tab-click="handleClick"
      @tab-remove="handleRemove"
      closable
    >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.path"
        :label="tab.title"
        :name="tab.path"
      ></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { TabsPaneContext, TabPaneName } from 'element-plus'
// import store from '@/store';
import useAppStore from '@/store/modules/app'

//appStore
const appStore = useAppStore()

//路由实例
const router = useRouter()
//当前激活路由配置信息
const route = useRoute()
//所有已访问路由标签
const tabs = computed(() => appStore.tabs)

//当前激活想标签的name
const activeName = ref<string>('')

/**
 * 监视路由的变化
 */
watch(
  () => route,
  (newRoute) => {
    console.log('route:', newRoute)
    activeName.value = newRoute.path
  },
  {
    immediate: true,
    deep: true,
  },
)

/**
 * 点击跳转页面
 */
const handleClick = (tab: TabsPaneContext) => {
  console.log(tab.props.name)
  router.push(tab.props.name as any)
}

/**
 * 点击删除标签页
 */
const handleRemove = (name: TabPaneName) => {
  console.log('remove', name, 'active', activeName.value)
  //当前删除的标签是正访问路由信息的标签，则跳转页面
  let jumpPath = ''
  if (name === activeName.value) {
    //确定向哪个路由路径进行跳转
    const index = tabs.value.findIndex((tab) => tab.path === name)
    //判断是否为数组中最后一项的下标，如果是最后一项，则跳转路径应向前一项
    //查找，如果不是最后一项，则向后一项查找
    if (index === tabs.value.length - 1) {
      jumpPath = tabs.value[index - 1].path
    } else {
      jumpPath = tabs.value[index + 1].path
    }
  }
  appStore.removeTab(name as string)
  //跳转路由
  router.push(jumpPath)
}
</script>

<style scoped lang="less">
.demo-tabs > .el-tabs__content {
  padding: 32px;
  font-size: 32px;
  color: #6b778c;
  font-weight: 600;
}

.nav-tab {
  float: left;
  width: 900px;
  // background-color: aqua;
}
</style>
